// ==UserScript==
// @name         成都住建一房一价表格优化
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  优化成都住建一房一价网站的表格展示
// @author       Your name
// @match        https://zw.cdzjryb.com/roompricezjw/index.html*
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @resource     DTCSS https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css
// @require      https://code.jquery.com/jquery-3.6.0.min.js
// @require      https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js
// ==/UserScript==

(function () {
    'use strict';

    // 添加日志函数
    const log = (...args) => {
        console.log('[房价表优化]', ...args);
    };

    // 添加 DataTables CSS
    try {
        const dtCSS = GM_getResourceText('DTCSS');
        GM_addStyle(dtCSS);
    } catch (error) {
        log('加载 DataTables CSS 失败:', error);
    }

    // 添加新拟态风格CSS
    GM_addStyle(`
        .neo-table-container {
            border-radius: 20px;
            background: #e0e0e0;
            box-shadow: 20px 20px 60px #bebebe, -20px -20px 60px #ffffff;
            padding: 20px;
            margin: 20px;
        }
        
        .dataTables_wrapper {
            padding: 20px;
            background: #e0e0e0;
            border-radius: 15px;
        }
        
        .stats-container {
            margin-top: 20px;
            padding: 20px;
            border-radius: 10px;
            background: #e0e0e0;
            box-shadow: inset 5px 5px 10px #bebebe, inset -5px -5px 10px #ffffff;
        }
        
        .stats-container h3 {
            margin: 0 0 20px 0;
            color: #1e88e5;
            font-size: 18px;
            text-align: center;
            text-shadow: 1px 1px 2px #ffffff;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            padding: 10px;
        }
        
        .stats-item {
            padding: 15px;
            border-radius: 12px;
            background: linear-gradient(145deg, #e6e6e6, #ffffff);
            box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
            transition: transform 0.3s ease;
        }
        
        .stats-item:hover {
            transform: translateY(-2px);
        }
        
        .stats-item-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        
        .stats-item-value {
            font-size: 18px;
            font-weight: bold;
            color: #1e88e5;
        }
        
        .stats-item.highlight {
            background: linear-gradient(145deg, #e3f2fd, #bbdefb);
        }
        
        .stats-item.warning {
            background: linear-gradient(145deg, #fff3e0, #ffe0b2);
        }
        
        .stats-item.success {
            background: linear-gradient(145deg, #e8f5e9, #c8e6c9);
        }
    `);

    // 等待元素出现的函数
    function waitForElement(selector, timeout = 10000) {
        return new Promise((resolve, reject) => {
            const startTime = Date.now();

            const checkElement = () => {
                const element = document.querySelector(selector);
                if (element) {
                    resolve(element);
                    return;
                }

                if (Date.now() - startTime > timeout) {
                    reject(new Error(`等待元素 ${selector} 超时`));
                    return;
                }

                setTimeout(checkElement, 100);
            };

            checkElement();
        });
    }

    // 主函数
    async function enhanceTable() {
        try {
            log('开始增强表格功能');

            // 等待原始表格加载
            const originalTable = await waitForElement('.table-theme-gray.tbl-room:not(.tbl-fix) table');
            log('找到原始表格');

            // 确保 jQuery 已加载
            if (typeof jQuery === 'undefined') {
                throw new Error('jQuery 未加载');
            }

            // 提取表格数据
            const headers = Array.from(originalTable.querySelectorAll('thead th')).map(th => th.textContent.trim());
            const rows = Array.from(originalTable.querySelectorAll('tbody tr')).map(tr =>
                Array.from(tr.querySelectorAll('td')).map(td => {
                    // 处理销售状态、抵押和查封的图标
                    const icon = td.querySelector('.icon');
                    if (icon) {
                        return icon.textContent.trim();
                    }
                    return td.textContent.trim();
                })
            );

            log(`获取到 ${rows.length} 行数据`);

            // 创建新容器
            const container = document.createElement('div');
            container.className = 'neo-table-container';

            // 添加统计区域 - 移到这里，在表格之前
            const statsContainer = document.createElement('div');
            statsContainer.className = 'stats-container';
            container.appendChild(statsContainer);

            // 创建表格容器
            const tableContainer = document.createElement('div');
            tableContainer.className = 'table-container';
            tableContainer.style.marginTop = '20px'; // 添加与统计区域的间距

            // 创建新表格HTML字符串
            let tableHtml = '<table id="enhanced-table" class="display"><thead><tr>';
            headers.forEach(header => {
                tableHtml += `<th>${header}</th>`;
            });
            tableHtml += '</tr></thead><tbody>';

            rows.forEach(row => {
                tableHtml += '<tr>';
                row.forEach(cell => {
                    tableHtml += `<td>${cell}</td>`;
                });
                tableHtml += '</tr>';
            });
            tableHtml += '</tbody></table>';

            tableContainer.innerHTML = tableHtml;
            container.appendChild(tableContainer);

            // 隐藏原表格并插入新表格
            const originalTableContainer = originalTable.closest('.table-view-wrap');
            originalTableContainer.style.display = 'none';
            originalTableContainer.parentNode.insertBefore(container, originalTableContainer);

            // 初始化 DataTable
            const dataTable = $('#enhanced-table').DataTable({
                language: {
                    url: 'https://cdn.datatables.net/plug-ins/1.10.24/i18n/Chinese.json'
                },
                pageLength: 25,
                dom: '<"top"lf>rt<"bottom"ip>',
                initComplete: function () {
                    updateStats();
                }
            });

            // 统计函数
            function updateStats() {
                try {
                    const areaColumn = 3; // 建筑面积列
                    const priceColumn = 5; // 清水价格列
                    const decorationColumn = 6; // 装修价格列

                    const validRows = rows.filter(row => !row[priceColumn].includes('*'));
                    const areas = validRows.map(row => parseFloat(row[areaColumn]));
                    const prices = validRows.map(row => parseFloat(row[priceColumn].replace(/[^\d.]/g, '')));
                    const decorationPrices = validRows.map(row => parseFloat(row[decorationColumn].replace(/[^\d.]/g, '')));

                    const totalArea = areas.reduce((a, b) => a + b, 0);
                    const avgPrice = prices.length ? prices.reduce((a, b) => a + b, 0) / prices.length : 0;
                    const avgPricePerSqm = prices.length ? prices.reduce((a, b, i) => a + b / areas[i], 0) / prices.length : 0;
                    const maxPrice = prices.length ? Math.max(...prices) : 0;
                    const minPrice = prices.length ? Math.min(...prices) : 0;

                    statsContainer.innerHTML = `
                        <h3>房源统计分析</h3>
                        <div class="stats-grid">
                            <div class="stats-item highlight">
                                <div class="stats-item-label">总房源数量</div>
                                <div class="stats-item-value">${rows.length} 套</div>
                            </div>
                            <div class="stats-item success">
                                <div class="stats-item-label">可售房源</div>
                                <div class="stats-item-value">${rows.filter(row => row[8].includes('可售')).length} 套</div>
                            </div>
                            <div class="stats-item warning">
                                <div class="stats-item-label">已售房源</div>
                                <div class="stats-item-value">${rows.filter(row => row[8].includes('已售')).length} 套</div>
                            </div>
                            <div class="stats-item">
                                <div class="stats-item-label">总建筑面积</div>
                                <div class="stats-item-value">${totalArea.toFixed(2)} ㎡</div>
                            </div>
                            <div class="stats-item highlight">
                                <div class="stats-item-label">平均总价</div>
                                <div class="stats-item-value">${(avgPrice / 10000).toFixed(2)} 万元</div>
                            </div>
                            <div class="stats-item highlight">
                                <div class="stats-item-label">平均单价</div>
                                <div class="stats-item-value">${avgPricePerSqm.toFixed(2)} 元/㎡</div>
                            </div>
                            <div class="stats-item">
                                <div class="stats-item-label">最高总价</div>
                                <div class="stats-item-value">${(maxPrice / 10000).toFixed(2)} 万元</div>
                            </div>
                            <div class="stats-item">
                                <div class="stats-item-label">最低总价</div>
                                <div class="stats-item-value">${(minPrice / 10000).toFixed(2)} 万元</div>
                            </div>
                        </div>
                    `;
                } catch (error) {
                    log('统计计算出错:', error);
                }
            }

            log('表格增强完成');
        } catch (error) {
            log('表格增强失败:', error);
            console.error(error);
        }
    }

    // 确保页面完全加载后再执行
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => setTimeout(enhanceTable, 1000));
    } else {
        setTimeout(enhanceTable, 1000);
    }
})();
